package com.vtb.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.renren.api.client.RenrenApiClient;
import com.renren.api.client.param.impl.AccessToken;
import com.renren.api.client.utils.HttpURLUtils;
import com.vtb.base.VtbBaseServlet;
import com.vtb.entity.Config;
import com.vtb.entity.RrDetailInfo;
import com.vtb.entity.RrOauth;
import com.vtb.entity.User;
import com.vtb.servlet.WtbException;


@SuppressWarnings("serial")
public class RrTokenUtils extends VtbBaseServlet {

	/**
	 * 获取包含accesstoken的json字符串
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @author Chen Tao
	 * @date 2012-7-3 上午10:47:36
	 */
	@SuppressWarnings("null")
    public RrOauth getAccessToken(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String code = request.getParameter("code");
		RrOauth rrOauth = null;
		if (code == null || code.length() == 0) {
			rrOauth.setUni("code");
			return rrOauth;
		}
		String rrOAuthTokenEndpoint = Config.RR_TOKEN_URL;
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("client_id", Config.RR_APP_KEY);
		parameters.put("client_secret", Config.RR_APP_SECRET);
		parameters.put("redirect_uri", Config.RR_REDIRECT_URL
				+ "/RrOauthServlet"); //与取code时一致
		parameters.put("grant_type", "authorization_code");
		parameters.put("code", code);
		String tokenResult = HttpURLUtils.doPost(rrOAuthTokenEndpoint,
				parameters);
		rrOauth = getOauthInfo(tokenResult, request);
		return rrOauth;
	}

	/**
	 * 使用refresh_token刷新access_token
	 *
	 * @param rrOauth
	 * @return
	 * @author Chen Tao
	 * @date 2012-7-3 上午10:47:28
	 */
	public static RrOauth refreshAccessToken(RrOauth rrOauth) {
		PostMethod method = new PostMethod(Config.RR_TOKEN_URL);
		method.addParameter("client_id", Config.RR_APP_KEY);
		method.addParameter("client_secret",Config.RR_APP_SECRET);
		method.addParameter("refresh_token", rrOauth.getRefresh_token());
		method.addParameter("grant_type", "refresh_token");
		HttpClient client = new HttpClient();
		try {
			client.executeMethod(method);
			InputStream result = method.getResponseBodyAsStream();
			org.json.JSONObject jsonObj;
				StringBuffer accessline = new StringBuffer();
				BufferedReader in = new BufferedReader(new InputStreamReader(
						result, "UTF-8"));
				String line;
				while ((line = in.readLine()) != null) {
					accessline.append(line);
				}
				jsonObj = new org.json.JSONObject(accessline.toString());
				rrOauth.setAccess_token(jsonObj.getString("access_token"));
				rrOauth.setExpires_in(jsonObj.getInt("expires_in"));
				rrOauth.setRefresh_token(jsonObj.getString("refresh_token"));
				rrOauth.setCreateTime(DateUtils.createTime());
		} catch (Exception e) {
			throw new WtbException("refreshToken换取失败",e);
		} 
		return rrOauth;
	}

	/**
	 * 获取用户的基本信息
	 *
	 * @param rrOauth
	 * @return
	 * @author Chen Tao
	 * @date 2012-7-3 上午10:47:21
	 */
	public RrDetailInfo getUserInfo(RrOauth rrOauth) {
		RrDetailInfo rrDetailInfo = null;
		if (rrOauth != null) {
			RenrenApiClient apiClient = RenrenApiClient.getInstance();
			int rrUid = apiClient.getUserService().getLoggedInUser(
					new AccessToken(rrOauth.getAccess_token()));
			JSONArray userInfo = apiClient.getUserService().getInfo(
					String.valueOf(rrUid), "name,sex,hometown_location,university_history,headurl",
					new AccessToken(rrOauth.getAccess_token()));
			if (userInfo != null && userInfo.size() > 0) {
				JSONObject currentUser = (JSONObject) userInfo.get(0);
				if (currentUser != null) {
					rrOauth.setUni(String.valueOf(rrUid));     //把用户信息编号设置为uni
					String name = (String) currentUser.get("name");
					String headurl = (String) currentUser.get("headurl");
					String sex = String.valueOf((Long) currentUser.get("sex"));
					JSONObject hometwon_json = (JSONObject) currentUser.get("hometown_location");
					String hometown = hometwon_json.get("province")+" "+hometwon_json.get("city");
					JSONArray universiyt_array = (JSONArray) currentUser.get("university_history");
					String university = null;
					if (!universiyt_array.isEmpty()) {
						JSONObject university_json = (JSONObject) universiyt_array.get(0);
						university = university_json.get("name")+" "+university_json.get("department")+" "+university_json.get("year");
					}
					User user = new User(name, headurl);
					rrDetailInfo = new RrDetailInfo(rrOauth.getAccess_token(),rrOauth.getRefresh_token(),rrOauth.getExpires_in(),rrOauth.getUni(),name,sex,hometown,university,"","");
					rrDetailInfo.setUser(user);
				}
			}
		}
		return rrDetailInfo;
	}

	/**
	 * 保存 refresh_token , access_token
     * 获取的RrOauth中 uni 和 ref 为空
	 *
	 * @param responseJson
	 * @param request
	 * @return
	 * @author Chen Tao
	 * @date 2012-7-3 上午10:47:05
	 */
	private static RrOauth getOauthInfo(String responseJson,
			HttpServletRequest request) {
		JSONObject tokenJson = (JSONObject) JSONValue.parse(responseJson);
		RrOauth rrOauth = null;
		if (tokenJson != null) {
			String accessToken = (String) tokenJson.get("access_token");
			Long expiresIn = (Long) tokenJson.get("expires_in");//距离过期时的时间段（秒数）
			String refresh_token = (String) tokenJson.get("refresh_token");//refreshToken
			rrOauth = new RrOauth(accessToken, refresh_token, expiresIn, "", "","");
		}
		return rrOauth;
	}
}
